package vn.axonactive.devday.jsf.model.security;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;

/**
 * Implement of a simple authentication provider with the user credential is configured in a properties file. 
 */
@ManagedBean
@ApplicationScoped
public class AuthenticationProvider {

	private Map<String, String> credentialRepo;
	
	public AuthenticationProvider()
	{
			Properties  props = new Properties();
			InputStream inputStream = getClass().getClassLoader().getResourceAsStream("../authentication.properties");
			if(inputStream==null)
			{
					throw new IllegalArgumentException("Faild to load /authentication.properties");
			}
			
			try {
				props.load(inputStream);
			} catch (IOException e) {
				throw new IllegalStateException(e);
			}
			
			if (props.size() % 2 != 0)
	        {
	            throw new IllegalStateException("/authentication.properties doesn't have legal data");
	        }
			
			credentialRepo = new HashMap<String, String>();
			
			for (int i = 1; i <= props.size() / 2; i++)
	        {

	            String userName = props.getProperty("user" + i + ".username");
	            String password = props.getProperty("user" + i + ".password");
	            
	            credentialRepo.put(userName, password);
	        }
			
	}
	
	/**
	 * Authenticate if given username/password is valid.
	 * 
	 * @param username
	 * @param password
	 * @return true if the given username/password is valid, otherwise return false.
	 */
	public synchronized boolean authenticate(final String username, final String password)
	{
		if(!credentialRepo.containsKey(username))
		{
			return false;
		}
		if(credentialRepo.get(username).equals(password))
		{
			return true;
		}
		return false;
	}

}
